package myservice.android.utilities;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;

public class ObservableScrollView extends ScrollView {		
	
	public interface OnScrollStoppedListener {
        public void onScrollStopped();
    }	

	private OnScrollStoppedListener onScrollStoppedListener = null;
	
	final static private int newCheck = 100;
	private Runnable scrollerTask;
	private int initialPosition;

    public ObservableScrollView(Context context) {
        super(context);
    }

    public ObservableScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public ObservableScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        
        scrollerTask = new Runnable() {

            public void run() {

                int newPosition = getScrollY();
                if(initialPosition - newPosition == 0) {//has stopped

                    if(onScrollStoppedListener!=null){

                        onScrollStoppedListener.onScrollStopped();
                    }
                } else {
                    initialPosition = getScrollY();
                    ObservableScrollView.this.postDelayed(scrollerTask, newCheck);
                }
            }
        };        
        
    }
    
    public void setOnScrollStoppedListener(OnScrollStoppedListener listener){
        onScrollStoppedListener = listener;
    }        	
    
    public void startScrollerTask(){

        initialPosition = getScrollY();
        ObservableScrollView.this.postDelayed(scrollerTask, newCheck);
    }    
	
}
